<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="逻辑回归," />





  <link rel="alternate" href="/blog/atom.xml" title="稻草人的编程之路" type="application/atom+xml" />






<meta name="description" content="逻辑回归上一篇博文我们推导了逻辑回归的公式，这一篇我们用代码实现一个逻辑回归算法，且给一个出国留学的数据集进行测试 熟悉数据 数据集  考试成绩与录取情况  密码:1uvq  数据读取  1234567import pandas as pdimport numpy as npimport matplotlib.pylab as pltpdData = pd.read_csv(&quot;LogiReg_da">
<meta name="keywords" content="逻辑回归">
<meta property="og:type" content="article">
<meta property="og:title" content="机器学习之逻辑回归（代码实现）">
<meta property="og:url" content="https://wangxiaochuang.github.io/2018/10/17/1.html">
<meta property="og:site_name" content="稻草人的编程之路">
<meta property="og:description" content="逻辑回归上一篇博文我们推导了逻辑回归的公式，这一篇我们用代码实现一个逻辑回归算法，且给一个出国留学的数据集进行测试 熟悉数据 数据集  考试成绩与录取情况  密码:1uvq  数据读取  1234567import pandas as pdimport numpy as npimport matplotlib.pylab as pltpdData = pd.read_csv(&quot;LogiReg_da">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2019-01-07T22:36:29.352Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="机器学习之逻辑回归（代码实现）">
<meta name="twitter:description" content="逻辑回归上一篇博文我们推导了逻辑回归的公式，这一篇我们用代码实现一个逻辑回归算法，且给一个出国留学的数据集进行测试 熟悉数据 数据集  考试成绩与录取情况  密码:1uvq  数据读取  1234567import pandas as pdimport numpy as npimport matplotlib.pylab as pltpdData = pd.read_csv(&quot;LogiReg_da">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://wangxiaochuang.github.io/2018/10/17/1.html"/>





  <title>机器学习之逻辑回归（代码实现） | 稻草人的编程之路</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">稻草人的编程之路</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">众人皆醉我独醒 举世皆浊我独清</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://wangxiaochuang.github.io/blog/2018/10/17/1.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="jackstraw">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="稻草人的编程之路">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">机器学习之逻辑回归（代码实现）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-10-17T00:18:05+00:00">
                2018-10-17
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/" itemprop="url" rel="index">
                    <span itemprop="name">机器学习</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/机器学习/逻辑回归（代码实现）/" itemprop="url" rel="index">
                    <span itemprop="name">逻辑回归（代码实现）</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/blog/2018/10/17/1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/blog/2018/10/17/1.html" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          
             <span id="/blog/2018/10/17/1.html" class="leancloud_visitors" data-flag-title="机器学习之逻辑回归（代码实现）">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="逻辑回归"><a href="#逻辑回归" class="headerlink" title="逻辑回归"></a>逻辑回归</h1><p>上一篇博文我们推导了逻辑回归的公式，这一篇我们用代码实现一个逻辑回归算法，且给一个出国留学的数据集进行测试</p>
<h2 id="熟悉数据"><a href="#熟悉数据" class="headerlink" title="熟悉数据"></a>熟悉数据</h2><ol>
<li>数据集</li>
</ol>
<p><a href="https://pan.baidu.com/s/1euBBz3n3Qou1EHSQFsrxsg">考试成绩与录取情况</a>  密码:1uvq</p>
<ol>
<li>数据读取</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> pandas <span class="keyword">as</span> pd</span><br><span class="line"><span class="keyword">import</span> numpy <span class="keyword">as</span> np</span><br><span class="line"><span class="keyword">import</span> matplotlib.pylab <span class="keyword">as</span> plt</span><br><span class="line"></span><br><span class="line">pdData = pd.read_csv(<span class="string">"LogiReg_data.txt"</span>, header=<span class="keyword">None</span>, names=[<span class="string">'Exam 1'</span>, <span class="string">'Exam 2'</span>, <span class="string">'Admitted'</span>])</span><br><span class="line">pdData.head()   <span class="comment"># 看下数据结果</span></span><br><span class="line">pdData.shape</span><br></pre></td></tr></table></figure>
<p>每个记录包含三个数据，成绩1、成绩2与是否录取</p>
<ol>
<li>我们根据是否录取作为结果来看下数据大致分布</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">positive = pdData[pdData[<span class="string">'Admitted'</span>] == <span class="number">1</span>]</span><br><span class="line">negative = pdData[pdData[<span class="string">'Admitted'</span>] == <span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">fig, ax = plt.subplots(figsize=(<span class="number">10</span>,<span class="number">5</span>))</span><br><span class="line">ax.scatter(positive[<span class="string">'Exam 1'</span>], positive[<span class="string">'Exam 2'</span>], s=<span class="number">30</span>, c=<span class="string">'b'</span>, marker=<span class="string">'o'</span>, label=<span class="string">'Admitted'</span>)</span><br><span class="line">ax.scatter(negative[<span class="string">'Exam 1'</span>], negative[<span class="string">'Exam 2'</span>], s=<span class="number">30</span>, c=<span class="string">'r'</span>, marker=<span class="string">'x'</span>, label=<span class="string">'Not Admitted'</span>)</span><br><span class="line">ax.legend()</span><br><span class="line">ax.set_xlabel(<span class="string">'Exam 1 Score'</span>)</span><br><span class="line">ax.set_ylabel(<span class="string">'Exam 2 Score'</span>)</span><br></pre></td></tr></table></figure>
<h2 id="编写代码"><a href="#编写代码" class="headerlink" title="编写代码"></a>编写代码</h2><p>总结一下，要完成的模块</p>
<ul>
<li>sigmoid：映射到概率的函数</li>
<li>model：返回预测结果值</li>
<li>cost：根据参数计算损失</li>
<li>gradient：计算每个参数的梯度方向</li>
<li>descent：进行参数更新</li>
<li>accuracy：计算精度</li>
</ul>
<ol>
<li>sigmoid</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">sigmoid</span><span class="params">(z)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> <span class="number">1</span> / (<span class="number">1</span> + np.exp(-z))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 大致看下sigmoid函数的图像</span></span><br><span class="line">nums = np.arange(<span class="number">-10</span>, <span class="number">10</span>, step=<span class="number">1</span>)</span><br><span class="line">fig, ax = plt.subplots(figsize=(<span class="number">12</span>, <span class="number">4</span>))</span><br><span class="line">ax.plot(nums, sigmoid(nums), <span class="string">'r'</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>model</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">model</span><span class="params">(X, theta)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> sigmoid(np.dot(X, theta.T))</span><br></pre></td></tr></table></figure>
<p>看一下我们需要什么样的数据？</p>
<script type="math/tex; mode=display">
(\theta_0 \quad \theta_1 \quad \theta_2) \quad \times \quad \begin{bmatrix}
1 \\ 
x_1 \\ 
x_2
\end{bmatrix} = \theta_0 + \theta_1 x_1 + \theta_2 x_2</script><script type="math/tex; mode=display">
(1 \quad x_1 \quad x_2) \quad \times \quad \begin{bmatrix}
\theta_0 \\ 
\theta_1 \\ 
\theta_2
\end{bmatrix} = \theta_0 + \theta_1 x_1 + \theta_2 x_2</script><p>我们将样本数据构造成符合上面公式的形式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">pdData.insert(<span class="number">0</span>, <span class="string">'Ones'</span>, <span class="number">1</span>)</span><br><span class="line">orig_data = pdData.values</span><br><span class="line">cols = orig_data.shape[<span class="number">1</span>]</span><br><span class="line">X = orig_data[:, <span class="number">0</span>:cols<span class="number">-1</span>]</span><br><span class="line">y = orig_data[:, cols<span class="number">-1</span>:cols]</span><br><span class="line">theta = np.zeros([<span class="number">1</span>, <span class="number">3</span>])</span><br><span class="line"><span class="comment">#自行打印各个数据，检查一下是否构造正常</span></span><br></pre></td></tr></table></figure>
<ol>
<li>cost</li>
</ol>
<p>将对数似然函数去负号</p>
<script type="math/tex; mode=display">
D(h_{\theta}(x), y) = -ylog(h_{\theta}(x)) - (1 - y)log(1 - h_{\theta}(x))</script><p>求平均损失</p>
<script type="math/tex; mode=display">
J(\theta) = \frac{1}{n} \sum_{i=1}^n D(h_{\theta}(x_i), y_i)</script><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">cost</span><span class="params">(X, y, theta)</span>:</span></span><br><span class="line">    left = np.multiply(-y, np.log(model(X, theta)))</span><br><span class="line">    right = np.multiply(<span class="number">1</span> - y, np.log(<span class="number">1</span> - model(X, theta)))</span><br><span class="line">    <span class="keyword">return</span> np.sum(left - right) / (len(X))</span><br><span class="line"></span><br><span class="line"><span class="comment"># 计算一下</span></span><br><span class="line">cost(X, y, theta)</span><br></pre></td></tr></table></figure>
<p>损失值能够求出来了，就可以以让损失值越小的方向调优了</p>
<ol>
<li>计算梯度（gradient）</li>
</ol>
<p>计算梯度的目的是为了找到参数更新的方向</p>
<p>计算梯度公式：</p>
<script type="math/tex; mode=display">\frac{\partial J}{\partial \theta_j} = - \frac{1}{m} \sum_{i=1}^m (y_i - h_{\theta}(x_i))x_{ij}</script><p>这里讲负号放到括号里面去</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">gradient</span><span class="params">(X, y, theta)</span>:</span></span><br><span class="line">    grad = np.zeros(theta.shape)</span><br><span class="line">    error = (model(X, theta) - y).ravel()</span><br><span class="line">    <span class="keyword">for</span> j <span class="keyword">in</span> range(len(theta.ravel())):</span><br><span class="line">        term = np.multiply(error, X[:,j])</span><br><span class="line">        grad[<span class="number">0</span>, j] = np.sum(term) / len(X)</span><br><span class="line">    <span class="keyword">return</span> grad</span><br></pre></td></tr></table></figure>
<ol>
<li>descent（进行梯度下降计算）</li>
</ol>
<p>我们的模型会进行非常多的迭代运算，那具体什么时候算结束呢</p>
<p>停止迭代策略</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">STOP_ITER = <span class="number">0</span>   <span class="comment"># 按迭代次数</span></span><br><span class="line">STOP_COST = <span class="number">1</span>   <span class="comment"># 按迭代前后两次的损失值变化大小</span></span><br><span class="line">STOP_GRAD = <span class="number">2</span>   <span class="comment"># 按迭代前后两次的梯度的变化大小</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">stopCriterion</span><span class="params">(type, value, threshold)</span>:</span></span><br><span class="line">    <span class="keyword">if</span> type == STOP_ITER:    <span class="keyword">return</span> value &gt; threshold</span><br><span class="line">    <span class="keyword">elif</span> type == STOP_COST:  <span class="keyword">return</span> abs(value[<span class="number">-1</span>] - value[<span class="number">-2</span>]) &lt; threshold</span><br><span class="line">    <span class="keyword">elif</span> type == STOP_GRAD:  <span class="keyword">return</span> np.linalg.norm(value) &lt; threshold</span><br></pre></td></tr></table></figure>
<p>我们的每次迭代都要打乱我们的数据</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">shuffleData</span><span class="params">(data)</span>:</span></span><br><span class="line">    np.random.shuffle(data)</span><br><span class="line">    cols = data.shape[<span class="number">1</span>]</span><br><span class="line">    X = data[:, <span class="number">0</span>:cols<span class="number">-1</span>]</span><br><span class="line">    y = data[:, cols<span class="number">-1</span>:]</span><br><span class="line">    <span class="keyword">return</span> X, y</span><br></pre></td></tr></table></figure>
<p>开始迭代</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="comment"># batchSize 有三个值，1：随机梯度下降，1-n：小批量梯度下降，n：全批量梯度下降</span></span><br><span class="line"><span class="comment"># alpha为学习率</span></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">descent</span><span class="params">(data, theta, batchSize, stopType, thresh, alpha)</span>:</span></span><br><span class="line">    init_time = time.time()</span><br><span class="line">    i = <span class="number">0</span>    <span class="comment"># 迭代次数</span></span><br><span class="line">    k = <span class="number">0</span>    <span class="comment"># batch</span></span><br><span class="line">    X, y = shuffleData(data)</span><br><span class="line">    grad = np.zeros(theta.shape)  <span class="comment"># 计算的梯度</span></span><br><span class="line">    costs = [cost(X, y, theta)]   <span class="comment"># 损失值</span></span><br><span class="line">    </span><br><span class="line">    <span class="keyword">while</span> <span class="keyword">True</span>:</span><br><span class="line">        grad = gradient(X[k:k+batchSize], y[k:k+batchSize], theta)    <span class="comment"># 计算梯度</span></span><br><span class="line">        k += batchSize    <span class="comment"># 取batch数量个数据</span></span><br><span class="line">        <span class="comment"># 判断是否超过了最大样本数</span></span><br><span class="line">        <span class="keyword">if</span> k &gt;= n:</span><br><span class="line">            k = <span class="number">0</span></span><br><span class="line">            X, y = shuffleData(data)  <span class="comment"># 重新洗牌</span></span><br><span class="line">        theta = theta - alpha * grad</span><br><span class="line">        costs.append(cost(X, y, theta)) <span class="comment"># 计算新的损失</span></span><br><span class="line">        i += <span class="number">1</span></span><br><span class="line">        </span><br><span class="line">        <span class="keyword">if</span> stopType == STOP_ITER:    value = i</span><br><span class="line">        <span class="keyword">elif</span> stopType == STOP_COST:  value = costs</span><br><span class="line">        <span class="keyword">elif</span> stopType == STOP_GRAD:    value = grad</span><br><span class="line">        <span class="keyword">if</span> stopCriterion(stopType, value, thresh): <span class="keyword">break</span></span><br><span class="line">        </span><br><span class="line">    <span class="keyword">return</span> theta, i<span class="number">-1</span>, costs, grad, time.time() - init_time</span><br></pre></td></tr></table></figure>
<ol>
<li>计算并画图看看结果吧</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">runExpe</span><span class="params">(data, theta, batchSize, stopType, thresh, alpha)</span>:</span></span><br><span class="line">    theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)</span><br><span class="line">    fig, ax = plt.subplots(figsize=(<span class="number">12</span>,<span class="number">4</span>))</span><br><span class="line">    ax.plot(np.arange(len(costs)), costs, <span class="string">'r'</span>)</span><br><span class="line">    ax.set_xlabel(<span class="string">'Iterations'</span>)</span><br><span class="line">    ax.set_ylabel(<span class="string">'Cost'</span>)</span><br><span class="line">    <span class="keyword">return</span> theta</span><br></pre></td></tr></table></figure>
<ol>
<li>对比不同的迭代停止策略</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 按迭代次数</span></span><br><span class="line">n = <span class="number">100</span> <span class="comment"># 我们的样本值就100，这里先使用全量迭代</span></span><br><span class="line">runExpe(orig_data, theta, n, STOP_ITER, thresh=<span class="number">5000</span>, alpha=<span class="number">0.000001</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按cost值变化大小</span></span><br><span class="line">runExpe(orig_data, theta, n, STOP_COST, thresh=<span class="number">0.000001</span>, alpha=<span class="number">0.001</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 按梯度值的变化大小</span></span><br><span class="line">runExpe(orig_data, theta, n, STOP_GRAD, thresh=<span class="number">0.05</span>, alpha=<span class="number">0.001</span>)</span><br></pre></td></tr></table></figure>
<ol>
<li>对比不同的样本策略对结果的影响</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 随机梯度下降</span></span><br><span class="line">runExpe(orig_data, theta, <span class="number">1</span>, STOP_ITER, thresh=<span class="number">0.05</span>, alpha=<span class="number">0.001</span>)</span><br><span class="line">runExpe(orig_data, theta, <span class="number">1</span>, STOP_ITER, thresh=<span class="number">15000</span>, alpha=<span class="number">0.000001</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment"># 小批量梯度下降</span></span><br><span class="line">runExpe(orig_data, theta, <span class="number">16</span>, STOP_ITER, thresh=<span class="number">15000</span>, alpha=<span class="number">0.001</span>)</span><br><span class="line"><span class="comment"># 可以看到结果也不好，这里我们对数据进行预处理一下，再看结果</span></span><br><span class="line"><span class="keyword">from</span> sklearn <span class="keyword">import</span> preprocessing <span class="keyword">as</span> pp</span><br><span class="line">scaled_data = orig_data.copy()</span><br><span class="line">scaled_data[:, <span class="number">1</span>:<span class="number">3</span>] = pp.scale(orig_data[:, <span class="number">1</span>:<span class="number">3</span>])</span><br><span class="line">theta = runExpe(scaled_data, theta, <span class="number">16</span>, STOP_ITER, thresh=<span class="number">15000</span>, alpha=<span class="number">0.001</span>)</span><br><span class="line"><span class="comment"># 可以明显看到差别</span></span><br><span class="line"><span class="comment"># 对数据进行预处理后的效果非常好</span></span><br></pre></td></tr></table></figure>
<ol>
<li>计算精度，看下模型效果如何</li>
</ol>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">predict</span><span class="params">(X, theta)</span>:</span></span><br><span class="line">    <span class="keyword">return</span> [<span class="number">1</span> <span class="keyword">if</span> x &gt;= <span class="number">0.5</span> <span class="keyword">else</span> <span class="number">0</span> <span class="keyword">for</span> x <span class="keyword">in</span> model(X, theta)]</span><br><span class="line"></span><br><span class="line">scaled_X = scaled_data[:, :<span class="number">3</span>]</span><br><span class="line">y = scaled_data[:, <span class="number">3</span>]</span><br><span class="line">predictions = predict(scaled_X, theta)</span><br><span class="line">correct = [<span class="number">1</span> <span class="keyword">if</span> ((a == <span class="number">1</span> <span class="keyword">and</span> b == <span class="number">1</span>) <span class="keyword">or</span> (a == <span class="number">0</span> <span class="keyword">and</span> b == <span class="number">0</span>)) <span class="keyword">else</span> <span class="number">0</span> <span class="keyword">for</span> (a, b) <span class="keyword">in</span> zip(predictions, y)]</span><br><span class="line">accuracy = (sum(map(int, correct))) % len(correct)</span><br><span class="line"><span class="keyword">print</span> (<span class="string">'accuracy = &#123;0&#125;%'</span>.format(accuracy))</span><br></pre></td></tr></table></figure>
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/逻辑回归/" rel="tag"># 逻辑回归</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/10/16/1.html" rel="next" title="机器学习之逻辑回归">
                <i class="fa fa-chevron-left"></i> 机器学习之逻辑回归
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/10/18/1.html" rel="prev" title="机器学习之其他细节">
                机器学习之其他细节 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpg"
                alt="jackstraw" />
            
              <p class="site-author-name" itemprop="name">jackstraw</p>
              <p class="site-description motion-element" itemprop="description">人生的意义，不在于最终获得了什么，而在于曾经努力追求过什么</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">分类</span>
                
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                
                  <span class="site-state-item-count">22</span>
                  <span class="site-state-item-name">标签</span>
                
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/blog/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#逻辑回归"><span class="nav-number">1.</span> <span class="nav-text">逻辑回归</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#熟悉数据"><span class="nav-number">1.1.</span> <span class="nav-text">熟悉数据</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#编写代码"><span class="nav-number">1.2.</span> <span class="nav-text">编写代码</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">jackstraw</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>访问人数
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>总访问量
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: true,
        notify: false,
        appId: 'lQM75w94ggNR0TjX61NLerrg-gzGzoHsz',
        appKey: 'I2wtQ2rd9KtoJmcEOiYG9zqT',
        placeholder: '如需帮助，请留下邮箱',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
    var infoEle = document.querySelector('#comments .info');
    if (infoEle && infoEle.childNodes && infoEle.childNodes.length > 0){
      infoEle.childNodes.forEach(function(item) {
        item.parentNode.removeChild(item);
      });
    }
  </script>



  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("lQM75w94ggNR0TjX61NLerrg-gzGzoHsz", "I2wtQ2rd9KtoJmcEOiYG9zqT");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
